<template>
    <div class="order-refund-apply-select-list" v-if="showKind">
        <van-nav-bar title="选择退款方式" :border="false" fixed placeholder/>
        <white-space/>
        <van-cell-group>
            <van-cell title="仅退款" label="未收到货，或无需退货仅退款" is-link @click="handleRefundKind('only_refund')">
                <template #icon>
                    <van-icon class="refund-icon" name="refund-o"/>
                </template>
            </van-cell>
            <van-cell title="退货退款" label="已收到货，需要退货并退款" is-link @click="handleRefundKind('return_refund')">
                <template #icon>
                    <van-icon class="refund-icon" name="exchange"/>
                </template>
            </van-cell>
        </van-cell-group>
    </div>
    <div class="order-refund-apply-select-list" v-else>
        <van-nav-bar title="选择退款商品" :border="false" fixed placeholder/>
        <white-space/>
        <order-refund-apply-select-list-item v-for="item in items" :key="item.id"
                                             v-model="item.checked" :disabled="item.disabled"
                                             :name="item.name" :image-url="item.imageUrl"
                                             :quantity="item.quantity" :total-amount="item.totalAmount"
                                             @change="handleChangeItemChecked"/>
        <van-submit-bar class="refund-items-submit-bar" button-text="下一步"
                        @submit="handleRouteToRefundListApply">
            <van-checkbox v-model="itemsChecked" :disabled="itemsDisabled">全选</van-checkbox>
        </van-submit-bar>
    </div>
</template>

<script>
  import BigDecimal from "decimal.js"
  import * as _ from "lodash"
  import { message, order as Order } from "@mall/api-services"
  import { Cell, CellGroup, Checkbox, Icon, NavBar, NoticeBar, SubmitBar, Toast } from "vant"
  import OrderRefundApplySelectListItem from "@/views/order/OrderRefundApplySelectListItem"
  import WhiteSpace from "@/components/WhiteSpace"

  export default {
    name: "OrderRefundApplySelectList",
    components: {
      WhiteSpace,
      OrderRefundApplySelectListItem,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [Checkbox.name]: Checkbox,
      [NavBar.name]: NavBar,
      [NoticeBar.name]: NoticeBar,
      [SubmitBar.name]: SubmitBar,
      [Icon.name]: Icon,
    },
    props: {
      orderId: String,
      itemIds: Array,
      kind: String,
    },
    watch: {
      "$route": "refreshOrder",
      order(order) {
        const { itemIds } = this
        this.items =
          _.chain(order.items)
            .map(item => ({
              id: item.id,
              name: item.name,
              imageUrl: item.imageUrl,
              quantity: item.quantity,
              totalAmount: item.totalAmount,
              checked: _.includes(itemIds, item.id),
              disabled: item.totalAmount === BigDecimal.add(item.refundedAmount, item.refundingAmount).toNumber(),
            }))
            .value()
      },
    },
    computed: {
      showKind() {
        return _.isEmpty(this.kind)
      },
      itemsDisabled() {
        const { items } = this
        for (const item of items) {
          if (!item.disabled) {
            return false
          }
        }
        return !_.isEmpty(items)
      },
      checkedItemIds() {
        return _.chain(this.items).filter(item => item.checked).map(item => item.id).join(",").value()
      },
      itemsChecked: {
        get() {
          for (const item of this.items) {
            if (!item.checked) {
              return false
            }
          }
          return true
        },
        set(checked) {
          for (const item of this.items) {
            item.checked = checked
          }
          this.routeToRefundList()
        },
      },
    },
    data() {
      return {
        order: new Order.Order(),
        items: [],
      }
    },
    created() {
      this.refreshOrder()
    },
    methods: {
      refreshOrder() {
        if (this.showKind && this.order) {
          return
        }
        Toast.loading()
        Order.OrderServiceV1
          .getOrder(this.orderId)
          .then(order => this.order = order)
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => Toast.clear())
      },
      routeToRefundList() {
        const { kind, checkedItemIds } = this
        this.$router.replace({
          path: `/orders/${this.orderId}/refunds`,
          query: {
            kind,
            item_ids: checkedItemIds,
          },
        })
      },
      handleRefundKind(kind) {
        this.$router.push({
          path: `/orders/${this.orderId}/refunds`,
          query: {
            kind,
          },
        })
      },
      handleChangeItemChecked() {
        this.routeToRefundList()
      },
      handleRouteToRefundListApply() {
        const { kind, orderId, checkedItemIds } = this
        this.$router.push({
          path: `/orders/${orderId}/refunds/apply`,
          query: {
            kind,
            order_id: orderId,
            item_ids: checkedItemIds,
          },
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
    @import "../../styles/variables";

    .order-refund-apply-select-list {
        .refund-icon {
            font-size: 24px;
            margin-right: 4px;
            color: $orange;
        }

        .refund-items-submit-bar {
            .van-submit-bar__bar {
                justify-content: space-between;
            }
        }

    }
</style>
